package cn.jathlon.math;

/**
 * 
 * @author tuxiao.czz
 * 
 */
public class MathUtils {

	/**
	 * si she wu ru!
	 * 
	 * @param d
	 * @param n
	 * @return
	 */
	public static double round(double d, int n) {
		double p = Math.pow(10, n);
		return Math.round(d * p) / p;
	}

	/**
	 * base 2;
	 * 
	 * @param x
	 * @return
	 */
	public static double log2(double x) {
		return Math.log(x) / Math.log(2);
	}
	
	/**
	 * sqrt(a^2 + b^2) without under/overflow.
	 * @param a
	 * @param b
	 * @return
	 */
	public static double hypot(double a, double b) {
		double r;
		if (Math.abs(a) > Math.abs(b)) {
			r = b / a;
			r = Math.abs(a) * Math.sqrt(1 + r * r);
		} else if (b != 0) {
			r = a / b;
			r = Math.abs(b) * Math.sqrt(1 + r * r);
		} else {
			r = 0.0;
		}
		return r;
	}
	
    /**
     * XXX DOC
     * 
     * @param array
     */
    public static double min(double[] array) {
        double min = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] < min)
                min = array[i];
        }
        return min;
    }
    
    /**
     * Return the maximum value in this array.
     * 
     * @param array
     *            the array to search the highest value for
     * @return the hightest value in the array
     */
    public static double max(double[] array) {
        double max = array[0];
        for (double d : array)
            if (d > max)
                max = d;
        return max;
    }
    
    /**
     * Computes the sum of the elements of an array of doubles.
     * 
     * @param doubles
     *            the array of double
     * @return the sum of the elements
     */
    public static double sum(double[] doubles) {

        double sum = 0;

        for (int i = 0; i < doubles.length; i++) {
            sum += doubles[i];
        }
        return sum;
    }
    /**
     * multiply
     * @param a
     * @param b
     * @return
     */
    public static double[] multiply(double[] a, double[] b) {
        double[] out = a.clone();
        for (int i = 0; i < out.length; i++)
            out[i] *= b[i];
        return out;
    }
    
    /**
     * Calculates the harmonic mean of the values in the supplied array.
     * 
     * @param g
     * @return
     */
    public static double harmonicMean(double[] g) {
        double sum = 0;
        for (double d : g)
            sum += 1 / d;
        return g.length / sum;
    }

    public static double arithmicMean(double[] g) {
        double sum = 0;
        for (double d : g)
            sum += d;
        return sum / g.length;
    }

	
	//////
	public static boolean zeroArray(double[] query){
		for (double d : query) {
			if(d > 0.0)
				return false;
		}
		return true;
	}

}
